<template>
    <el-breadcrumb :separator-icon="ArrowRight">
    <el-breadcrumb-item :to="{ path: '/' }">首页(登录)</el-breadcrumb-item>
    <el-breadcrumb-item>授权中心管理</el-breadcrumb-item>
    <el-breadcrumb-item>管理员管理</el-breadcrumb-item>
  </el-breadcrumb>
    <div>
       <el-card style="margin-top: 10px;">
          <el-form :inline="true" :model="searData" class="demo-form-inline">
    <el-form-item label="姓名">
      <el-input v-model="searData.UserNickname" placeholder="姓名" clearable />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="getUser">查询</el-button>
      <el-button type="success" @click="addUser">添加</el-button>
    </el-form-item>
  </el-form>
       </el-card>
       <el-card style="margin-top: 10px;">
        <el-breadcrumb-item>管理员列表</el-breadcrumb-item>
         <el-table :data="userData" border style="width: 100%">
    <el-table-column type="index" label="序号" width="75" align="center" />
    <el-table-column prop="userName" label="账号" align="center" />
    <el-table-column prop="userPass" label="密码" align="center">
        <template v-slot="scoped">
          <span>******</span>
        </template>
    </el-table-column>
    <el-table-column prop="userNickname" label="昵称" align="center" />
    <el-table-column prop="roleName" label="角色" align="center" />
    <el-table-column prop="status" label="是否启用" align="center">
        <template #default="scoped">
        <span v-if="scoped.row.status=='0'">启用</span>
        <span v-if="scoped.row.status=='1'">禁用</span>
        </template>
    </el-table-column>
    <el-table-column prop="createTime" label="创建时间" align="center">
        <template v-slot="scoped">
          {{ moment(scoped.row.createTime).format("YYYY-MM-DD HH:mm:ss") }}
        </template>
    </el-table-column>
    <el-table-column  label="操作"width="150" align="center">
        <template #default="scoped" >
            <el-button  type="warning" size="small" @click="editUser(scoped.row)">编辑</el-button>
            <el-button  type="danger" size="small" @click="DelUser(scoped.row)">删除</el-button>
        </template>
    </el-table-column>
  </el-table>
  <table>
    <tbody>
        <tr>
            <td>
                <el-pagination
      v-model:current-page="page.PageIndex"
      v-model:page-size="page.PageSize"
      :page-sizes="[1, 2, 3, 4,5]"
      :background="true"
      layout="total, sizes, prev, pager, next, jumper"
      :total="page.totalCount"
    />
            </td>
        </tr>
    </tbody>
  </table>
       </el-card>

        <!-- 添加/编辑用户弹窗 -->
       <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px" draggable>
        <el-form ref="ruleFormRef" :model="ruleForm" :rules="addRules" label-width="100px">
            <el-form-item label="用户名" prop="userName">
                <el-input v-model="ruleForm.userName" placeholder="请输入用户名" />
            </el-form-item>
            <el-form-item label="密码" prop="userPass">
                <el-input v-model="ruleForm.userPass" placeholder="请输入密码" show-password/>
            </el-form-item>
            <el-form-item label="用户昵称" prop="userNickname">
                <el-input v-model="ruleForm.userNickname" placeholder="请输入用户昵称"/>
            </el-form-item>
             <el-form-item label="角色" prop="roleIds">
      <el-checkbox-group v-model="ruleForm.roleIds">
        <el-checkbox v-for="item in roleData" :value="item.roleId" :label="item.roleName" name="type">
        </el-checkbox>
      </el-checkbox-group>
    </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitForm(ruleFormRef)">确定</el-button>
            </span>
        </template>
    </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref,watch } from 'vue'
import { ArrowRight } from '@element-plus/icons-vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
//import axios from 'axios'
import { useRouter } from 'vue-router'
//引入pinia
import { useCounterStore } from "@/stores/counter"
//pinia 变量
const counter = useCounterStore();
const router = useRouter()

import { dataRead,dataWrite } from '@/Utils/Http';
import moment from 'moment'

//钩子函数
onMounted(() => {
    getUser()
    bindRole()
})


// 类型定义
interface RuleForm  {
    userId: number;
    userName: string;
    userPass: string;
    userNickname: string;
    roleIds: [];
}
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<RuleForm>({
    userId:0,
    userName: '',
    userPass:'',
    userNickname: '',
    roleIds:[]
})

// 弹窗相关
const dialogVisible = ref(false);
const dialogTitle = ref('添加用户');
const formRef = ref<FormInstance>();
// const formData = reactive<FormData>({
//     permissionId: 0,
//     permissionName: '',
//     permissionUrl: ''
// });

// 添加表单验证规则（需要非空验证）
const addRules  = reactive<FormRules<RuleForm>>({
    userName: [
        { required: true, message: '请输入用户名', trigger: 'blur' }
    ],
    userPass: [
        { required: true, message: '请输入密码', trigger: 'blur' }
    ],
    userNickname: [
        { required: true, message: '请输入昵称', trigger: 'blur' }
    ],
    // roleIds: [
    //     { required: true, message: '请选择角色', trigger: 'change' }
    // ]
});

// 编辑表单验证规则（不需要非空验证）
const editRules  = reactive<FormRules<RuleForm>>({});

//查询条件
const searData = reactive({
    UserNickname:''
})
//分页条件
const page = reactive({
    PageIndex: 1,
    PageSize: 5,
    totalCount: 0,
    pageCount:0
})

//数据
const userData = ref<any>([])
const getUser = () => {
    dataRead.get('/BaseData/UserQuery', {
        params: {
            UserNickname: searData.UserNickname,
            PageIndex: page.PageIndex,
            PageSize:page.PageSize
    } }).then(res => {
        userData.value = res.data.data.data
        page.totalCount=res.data.data.totalCount
        page.pageCount=res.data.data.pageCount
    }).catch(

    )
}
watch(page, () => {
    getUser()
})
//绑定角色
const roleData = ref<any>([])
const bindRole = () => {
    dataRead.get('/BaseData/BindRole').then(res => {
        roleData.value=res.data.data
    })
}

// 添加用户
const addUser = () => {
    dialogTitle.value = '添加用户';
    ruleForm.userId = 0;
    ruleForm.userName = '';
    ruleForm.userPass = '';
    ruleForm.userNickname = '';
    ruleForm.roleIds = [];
    dialogVisible.value = true;
};

// 编辑用户
const editUser = (row: any) => {
    dialogTitle.value = '编辑用户';
    //角色Id存储的是集合记得赋值!!!!
    ruleForm.roleIds=row.roleId
   Object.assign(ruleForm,row)
    dialogVisible.value = true;
};

// 提交表单
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
        console.log('submit!')
        if (ruleForm.userId == 0)
        {
            if (ruleForm.roleIds.length == 0)
        {
                ElMessage.error('请选择角色!!!')
                return;    
        }
            dataWrite.post('/BaseData/AddUser',ruleForm).then(res => {
                if (res.data.code == 300)
                {
                    ElMessage.success('添加成功')
                    dialogVisible.value = false
                    getUser()
                }
                else if (res.data.data == -1)
                {
                    ElMessage.error(res.data.message)
                }
                else
                {
                 ElMessage.error('添加失败')
            }
          })
        }
        //修改
        else
        {
             dataWrite.post('/BaseData/UpdUser',ruleForm).then(res => {
                if (res.data.code == 400)
                {
                    ElMessage.success('修改成功')
                    dialogVisible.value = false
                    getUser()
                }
                else
                {
                 ElMessage.error('修改失败')
            }
          })
       }
    }
  })
}


const DelUser = (row:any) => {
    ElMessage.error('待完善')
     return
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

</script>

<style scoped>

</style>